package com.barks.learning.base.async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author chenw-i
 * @version 1.0.0
 * @ClassName DeferredResultListener.java
 * @Description TODO
 * @createTime 2020年07月11日 10:07:00
 */
@Component
public class DeferredResultListener implements ApplicationListener {

    private Logger logger = LoggerFactory.getLogger(DeferredResultListener.class);
    @Autowired
    TaskQueue taskQueue;

    @Autowired
    DeferredResultHolder holder;

    public DeferredResultListener(){
        logger.info("DeferredResultListener init = >");
    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        new Thread(() -> {
            while (true){
                String complete = taskQueue.getcompleteTask();
                if(complete != null){
                    Object object = taskQueue.getTaskResult(complete);
                    holder.getDeferredResult(complete).setResult(object);
                }
            }
        }).start();
    }
}
